package com.lyhengtongwl.zqsnews.utils;


import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.ui.activity.NewsContactUsActivity;
import com.tencent.mm.opensdk.channel.a.b;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NewsOpenShare {
    private Context mContext;
    private Map<String, String> map;
    //    public static final String invite_share_key = "com.UCMobile:wx020a535dccd46c11,
    //    com.tencent.mtt:wx64f9cf5b17af074d,
    //    com.baidu.browser.apps:wx0116bf301a92506b,
    //    com.ijinshan.browser_fast:wxc2ff198ba4a63f06,
    //    com.browser2345:wx66d367303dace3ad,
    //    sogou.mobile.explorer:wxf1d5d36b9ea492f8,
    //    com.qihoo.browser:wx60d9d5c44ca9386e,
    //    com.tencent.mobileqq:wxf0a80d0ac2e82aa7";

    private List<String> ownerAppIds;//存放自己的appId


    public NewsOpenShare(Context mContext) {
        this.mContext = mContext;
        ownerAppIds = new ArrayList<>();
        ownerAppIds.add("wxfc8bdef0b5e835e9");//一叶落知天下秋
        ownerAppIds.add("wx5a79abd679652479");//燕雀不知鸿鹄志
        ownerAppIds.add("wxb59de194cfa813d0");//书声朗朗
        ownerAppIds.add("wx1f8609d388a61a14");//简简单单做人
        ownerAppIds.add("wxbcaed7efb538e477");//智慧的代价是矛盾
        ownerAppIds.add("wxd243c18391733f39");//不是井里没有水
        ownerAppIds.add("wxe54bb234f78a6209");//看透人生心无所碍
        ownerAppIds.add("wx1324847996693e83");//空白昵称
        ownerAppIds.add("wxce430aee2899251d");//吉祥娃娃App
        ownerAppIds.add("wxac580e9b512a86f9");//大树App
        ownerAppIds.add("wx3b32e0e1d601baa1");//亨通App
        ownerAppIds.add("wx8815d296ccef566a");//赚钱树App

        map = new HashMap<>();
        String[] str = (AppConfig.getInstance(App.getContext()).get("pacg_appid")).split("\\|");
        map.put(str[0], str[1]);//搜狗浏览器


//        map.put("com.ijinshan.browser_fast", "wxc2ff198ba4a63f06");//猎豹浏览器
//        map.put("com.qihoo.browser", "wx60d9d5c44ca9386e");//360浏览器
//        map.put("com.tencent.mobileqq", "wxf0a80d0ac2e82aa7");//手机qq的
//        map.put("com.tencent.mtt", "wx64f9cf5b17af074d");//QQ浏览器的
//        map.put("com.ht.news", "wx548210ae36b5de58");//赚钱树的包名和appId


//        map.put("com.browser2345", "wx66d367303dace3ad");//2345浏览器


//        map.put("com.lyhengtongwl.zqsnews", "wx8815d296ccef566a");//赚钱树app的包名和appId
//
//        map.put("com.ss.android.article.news", "wx50d801314d9eb858");//wifi万能钥匙

    }

    private Bitmap GetLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        URL imageurl = null;

        try {
            imageurl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (imageurl == null) {
                return ImgHelper.getBitmapFormResources(mContext, R.mipmap.error);
            }
            HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //图标是连接的
    public void ShareUrlToWx(String title, String articleUrl, String imgUrl, String content, int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bm = GetLocalOrNetBitmap(imgUrl);
                if (bm == null) {
                    //如果获取图片失败  添加本地图片
                    bm = ImgHelper.getBitmapFormResources(mContext, R.mipmap.error);
                }
                //遍历map
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (CheckApkExist.checkApkExist(mContext, entry.getKey())) {
                        shareToWx(entry.getValue(), entry.getKey(), title, articleUrl, bm, content, scene);
                        break;
                    } else {
                        int ran = (int) (Math.random() * 12);
                        shareToWx(ownerAppIds.get(ran), "com.lyhengtongwl.zqsnews", title, articleUrl, bm, content, scene);
                    }
                }
            }
        }).start();

    }

    // 图标是本地的
    public void ShareUrlToWx(String title, String articleUrl, int imgUrl, String content, int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(mContext, R.mipmap.red_packet);
                //遍历map
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (CheckApkExist.checkApkExist(mContext, entry.getKey())) {
                        shareToWx(entry.getValue(), entry.getKey(), title, articleUrl, bitmapFormResources, content, scene);
                        break;
                    } else {
                        int ran = (int) (Math.random() * 11);
                        shareToWx(ownerAppIds.get(ran), "com.lyhengtongwl.zqsnews", title, articleUrl, bitmapFormResources, content, scene);
                    }
                }
            }
        }).start();

    }


    private void shareToWx(String appId, String appPackage, String title, String articleUrl, Bitmap bm, String content, int scene) {
        WXWebpageObject web = new WXWebpageObject();
        web.webpageUrl = articleUrl;
        final WXMediaMessage msg = new WXMediaMessage(web);
        msg.title = title;
        msg.description = content;
        msg.setThumbImage(bm);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = scene;
//        req.transaction=buildTransaction("Req");
        shareWxOrCircle(mContext, req, appId, appPackage);
    }

    private void shareWxOrCircle(Context mContext, SendMessageToWX.Req paramReq, String wxAppId, String appPackage) {
        try {
            Bundle bundle = new Bundle(); //
            paramReq.toBundle(bundle);
            String str2 = "weixin://sendreq?appid=" + wxAppId;   //sendreq
            Intent intent = new Intent().setClassName("com.tencent.mm", "com.tencent.mm.plugin.base.stub.WXEntryActivity");//
            intent.putExtras(bundle);
            intent.setAction("com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER");
            intent.putExtra("_mmessage_sdkVersion", 621019136);  //621019136   570490883
            intent.putExtra("_mmessage_appPackage", appPackage);
            intent.putExtra("_mmessage_content", str2);

//            intent.putExtra("_mmessage_support_content_type",System.currentTimeMillis());

            String buffer = str2 +
                    621019136 +
                    appPackage +
                    "mMcShCsTr";
            intent.putExtra("_mmessage_checksum", b.a(str2, 621019136, appPackage));
//            intent.putExtra("_mmessage_checksum", com.tencent.mm.opensdk.utils.b.e(buffer.substring(1, 9).getBytes()).getBytes());
            ((Activity) mContext).startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //分享图片 先保存 再分享
    public void shareImgToWXF(Bitmap bm) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(App.getContext().getContentResolver(), bm, null, null));
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
        mContext.startActivity(Intent.createChooser(intent, "收徒赚钱"));
    }

    //分享图片 先保存 再分享
    public void shareImgToWXFC(Bitmap bm) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bm, null, null));
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友
        mContext.startActivity(Intent.createChooser(intent, "收徒赚钱"));
    }

    //打开微信
    public void openWX() {
        if (PermissionUtils.getInstance().checkPermission(mContext,
                Manifest.permission.WRITE_CONTACTS)) {
            if (CheckApkExist.checkApkExist(mContext, "com.tencent.mm")) {
                Intent intent = new Intent();
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                mContext.startActivity(intent);
            } else {
                NewsToastUtils.showToast(mContext, "未安装手微信或安装的版本不支持！");
            }
        } else {
            PermissionUtils.getInstance().showSystemPermissionsSettingDialog((NewsContactUsActivity) mContext);
        }

    }
}
